// ChassisReceiveData.js

class ChassisReceiveData {
    constructor() {
        this.protobufRoot = null;
    }

    // 初始化 Protobuf
    async initProtobuf() {
        try {
            // 假设 mstf 是全局变量，包含了 protobuf 的定义
            if (typeof mstf !== 'undefined') {
                this.protobufRoot = protobuf.Root.fromJSON(mstf);
                console.log("Protobuf initialized successfully");
            } else {
                throw new Error('mstf protobuf definitions not found');
            }
        } catch (error) {
            console.error('Failed to initialize protobuf:', error);
            throw error;
        }
    }

    // 初始化连接
    async init() {
        try {
            // 先初始化 Protobuf
            await this.initProtobuf();
        } catch (error) {
            console.error('Initialization failed:', error);
            throw error;
        }
    }

    // 消息处理
    handleMessage(event) {
        if (event.data instanceof ArrayBuffer) {
            this.handleBinaryMessage(event.data);
        } else {
            console.log('Received text message:', event.data);
        }
    }

    // 处理二进制消息
    handleBinaryMessage(data) {
        try {
            const message = this.protobufRoot.lookupType('mstf.camb.proto.RemoteXferMessage')
                .decode(new Uint8Array(data));

            if (message.chass_misc?.info) {
                this.handleChassisMiscInfo(message.chass_misc.info);
            }
        } catch (error) {
            console.error('解码消息错误:', error);
        }
    }

    handleChassisMiscInfo(info) {
        const stateUpdates = {
            'motion.wheels.left.rotating': info.wheels?.wheel_left?.en?.value,
            'cleaning.brush.main.enabled': info.brushs?.roll_brush_main?.en?.value,
            'cleaning.brush.side.enabled': info.brushs?.side_brush_left?.en?.value,
            'cleaning.vacuum.enabled': info.suck_fan?.suck_fan_1?.en?.value
        };

        Object.entries(stateUpdates).forEach(([key, value]) => {
            if (value !== undefined) {
                window.ComponentStateTestPanel.instance?.stateManager.updateComponentState(key, value);
            }
        });
    }
    // 处理解码后的消息
    decodeMessage(message) {
        //console.log("Decoded message:", JSON.stringify(message, null, 2));
        // Handle different message types
        if (message.systemInfo) {
            this.handleSystemInfo(message.systemInfo.info);
        } else if (message.volatileInfo) {
            this.handleVolatileInfo(message.volatileInfo.info);
        } else if (message.modeStatus) {
            this.handleModeStatus(message.modeStatus.info);
        } else if (message.chassMisc && message.chassMisc.info) {
            this.handleChassisMiscData(message.chassMisc.info);
        } else if (message.chassRaw && message.chassRaw.info) {
            this.handleChassisRawData(message.chassRaw.info);
        }
    }

    handleSystemInfo(info) {
        // 更新系统信息UI
        console.log("System Info:", info);
        // TODO: 更新相关UI元素
    }

    handleVolatileInfo(info) {
        // 处理易变信息
        console.log("Volatile Info:", info);
        // TODO: 更新相关状态和UI
    }

    handleModeStatus(info) {
        // 更新模式状态
        console.log("Mode Status:", info);
        // TODO: 更新模式相关UI和状态
    }

    handleChassisMiscData(chassisData) {
        if (chassisData.tankBox) {
            this.handleTankBoxInfo(chassisData.tankBox);
        }
        if (chassisData.brushs) {
            this.handleBrushInfo(chassisData.brushs);
        }
        if (chassisData.suckFan) {
            this.handleSuckFanInfo(chassisData.suckFan);
        }
        if (chassisData.mop) {
            this.handleMopInfo(chassisData.mop);
        }
        if (chassisData.wheels) {
            this.handleWheelsInfo(chassisData.wheels);
        }
        if (chassisData.battery) {
            this.handleBatteryInfo(chassisData.battery);
        }
        if (chassisData.leds) {
            this.handleLedsInfo(chassisData.leds);
        }
        if (chassisData.keys) {
            this.handleKeysInfo(chassisData.keys);
        }
        if (chassisData.bumps) {
            this.handleBumpsInfo(chassisData.bumps);
        }
        if (chassisData.drops) {
            this.handleDropsInfo(chassisData.drops);
        }
        if (chassisData.dtofs) {
            this.handleDtofsInfo(chassisData.dtofs);
        }
        // updateRobotComponentsState(robotState);
    }

    handleWheelsInfo(info) {
        setWheelRotateState(0, info.left.rot, info.left.speed / 100);
        setWheelRotateState(1, info.right.rot, info.right.speed / 100);
        setWheelOffGroundState(0, !info.left.off);
        setWheelOffGroundState(1, !info.right.off);
    }

    // 处理刷子信息更新
    handleBrushInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager) return;

        if (info.sideBrushRight) {
            let sideBrushState = {
                rotating: false,
                speed: 0
            };

            if (info.sideBrushRight.en) {
                sideBrushState.rotating = info.sideBrushRight.en.value;
            }
            if (info.sideBrushRight.val) {
                sideBrushState.speed = info.sideBrushRight.val.value / 10;
            }

            setSideBrushRotation(sideBrushState.rotating, sideBrushState.speed);
        }

        if (info.rollBrushFront) {
            let mainBrushState = {
                rotating: false,
                speed: 0
            };

            if (info.rollBrushFront.en) {
                mainBrushState.rotating = info.rollBrushFront.en.value;
            }
            if (info.rollBrushFront.val) {
                mainBrushState.speed = info.rollBrushFront.val.value / 20;
            }

            setMainBrushRotation(mainBrushState.rotating, mainBrushState.speed);
        }
    }

    // 处理DTOF传感器信息
    handleDtofsInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager || !info || !info.dtof_1) return;

        const isEnabled = info.dtof_1.en ? info.dtof_1.en.value : false;
        const distance = info.dtof_1.val ? info.dtof_1.val.value : 0;

        stateManager.updateComponent('sensors.tof', {
            enabled: isEnabled,
            distance: distance
        });

        setTofSensorState(isEnabled, distance);
    }

    // 初始化点云对象
    handleChassisRawData(chassisData) {
        if (chassisData.dPcl) {
            const data = chassisData.dPcl;
            // 打印第一个点的数据用于调试
            /*
            if (data.points && data.points.length > 0) {
                console.log('Sample first point data:', {
                    point: data.points[0],
                    total_points: data.points.length,
                    frameId: data.header ? data.header.frameId : 'unknown'
                });
            }
            */
            pointCloudProcessor.updatePointCloud(chassisData.dPcl);
        }
    }

    // 更新处理水箱和尘盒信息的函数
    handleTankBoxInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager || !info) return;

        if (info.cleanTank) {
            if (info.cleanTank.en !== undefined) {
                stateManager.updateComponent('waterTank.attached', info.cleanTank.en.value);
            }
            if (info.cleanTank.val !== undefined) {
                stateManager.updateComponent('waterTank.waterLevel', info.cleanTank.val.value);
            }
            updateWaterTankState();
        }

        if (info.dustBox) {
            if (info.dustBox.en !== undefined) {
                stateManager.updateComponent('dustBin.attached', info.dustBox.en.value);
            }
            if (info.dustBox.val !== undefined) {
                stateManager.updateComponent('dustBin.fullness', info.dustBox.val.value);
            }
            updateDustBoxState();
        }
    }

    // 处理吸风机状态更新
    handleSuckFanInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager || !info || !info.suckFan_1) return;

        let fanState = {
            enabled: false,
            speed: 0
        };

        if (info.suckFan_1.en !== undefined) {
            fanState.enabled = info.suckFan_1.en.value;
        }

        if (info.suckFan_1.val !== undefined) {
            fanState.speed = info.suckFan_1.val.value / 10;
        }

        stateManager.updateComponent('cleaning.vacuum.enabled', fanState.enabled);
        stateManager.updateComponent('cleaning.vacuum.fanSpeed', fanState.speed);

        setFanRotation(fanState.enabled, fanState.speed);
    }

    // 拖布信息处理函数
    handleMopInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager || !info) return;

        if (info.lift?.en !== undefined) {
            stateManager.updateComponent('mopping.lifted', info.lift.en.value);
        }

        if (info.work) {
            if (info.work.en !== undefined) {
                stateManager.updateComponent('mopping.enabled', info.work.en.value);
            }
            if (info.work.val !== undefined) {
                stateManager.updateComponent('mopping.workMode', info.work.val.value / 50);
            }
        }

        if (info.water) {
            if (info.water.en !== undefined) {
                stateManager.updateComponent('mopping.waterEnabled', info.water.en.value);
            }
            if (info.water.val !== undefined) {
                stateManager.updateComponent('mopping.waterLevel', info.water.val.value);
            }
        }

        setMopState();
    }

    handleBumpsInfo(info) {
        if (info.bumpLidarF && info.bumpLidarF.en) {
            updateLidarKeyState('lidarKeyFront', info.bumpLidarF.en.value);
        }
        if (info.bumpLidarB && info.bumpLidarB.en) {
            updateLidarKeyState('lidarKeyBack', info.bumpLidarB.en.value);
        }
        if (info.bumpLidarL && info.bumpLidarL.en) {
            updateLidarKeyState('lidarKeyLeft', info.bumpLidarL.en.value);
        }
        if (info.bumpLidarR && info.bumpLidarR.en) {
            updateLidarKeyState('lidarKeyRight', info.bumpLidarR.en.value);
        }
        if (info.bumpLeft && info.bumpLeft.en) {
            updateBumperState('left', info.bumpLeft.en.value);
        }
        if (info.bumpRight && info.bumpRight.en) {
            updateBumperState('right', info.bumpRight.en.value);
        }
    }

    handleBatteryInfo(info) {
        if (info.batteryInfo && info.batteryInfo.val) {
            const newLevel = Math.max(0, Math.min(1, info.batteryInfo.val.value / 100));
            console.log("Received battery update:", info.batteryInfo.val.value, "newLevel:", newLevel);
            // 状态更新时会自动触发监听器，进而更新UI和3D模型
            this.updateComponentState({
                working: {
                    ...this.state.working,
                    batteryLevel: newLevel
                }
            });
        }
    }

    // 处理LED状态更新
    handleLedsInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager || !info) return;

        // 处理电源键LED
        if (info.turnLeftLed?.en !== undefined) {
            stateManager.updateComponent('interface.powerButton.ledOn', info.turnLeftLed.en.value);
        }

        // 处理充电键LED
        if (info.turnRightLed?.en !== undefined) {
            stateManager.updateComponent('interface.rechargeButton.ledOn', info.turnRightLed.en.value);
        }

        // 更新3D模型显示
        const powerState = {
            pressed: stateManager.getComponentState('interface.powerButton.pressed'),
            ledOn: stateManager.getComponentState('interface.powerButton.ledOn')
        };

        const rechargeState = {
            pressed: stateManager.getComponentState('interface.rechargeButton.pressed'),
            ledOn: stateManager.getComponentState('interface.rechargeButton.ledOn')
        };

        update3DButtonState('powerButton', powerState.pressed, powerState.ledOn);
        update3DButtonState('rechargeButton', rechargeState.pressed, rechargeState.ledOn);
    }

    // 处理按键状态更新
    handleKeysInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager || !info) return;

        // 处理电源键
        if (info.power?.en !== undefined) {
            stateManager.updateComponent('interface.powerButton.pressed', info.power.en.value);
        }

        // 处理充电键
        if (info.dock?.en !== undefined) {
            stateManager.updateComponent('interface.rechargeButton.pressed', info.dock.en.value);
        }

        // 更新3D模型显示
        const powerState = {
            pressed: stateManager.getComponentState('interface.powerButton.pressed'),
            ledOn: stateManager.getComponentState('interface.powerButton.ledOn')
        };

        const rechargeState = {
            pressed: stateManager.getComponentState('interface.rechargeButton.pressed'),
            ledOn: stateManager.getComponentState('interface.rechargeButton.ledOn')
        };

        update3DButtonState('powerButton', powerState.pressed, powerState.ledOn);
        update3DButtonState('rechargeButton', rechargeState.pressed, rechargeState.ledOn);
    }

    // 处理掉落传感器信息
    handleDropsInfo(info) {
        const stateManager = window.robotStateManager;
        if (!stateManager || !info) return;

        const dropSensors = {
            dropLeft: 'left',
            dropLeftMid: 'frontLeft',
            dropRightMid: 'frontRight',
            dropRight: 'right'
        };

        Object.entries(dropSensors).forEach(([key, position]) => {
            if (info[key] && info[key].en !== undefined) {
                const isActive = info[key].en.value;
                stateManager.updateComponent(`sensors.cliff.${position}`, isActive);

                // 找到对应的传感器索引并更新视觉效果
                const index = Object.values(dropSensors).indexOf(position);
                if (index !== -1) {
                    setCliffSensorState(index, isActive);
                }
            }
        });
    }
}

// 创建全局实例
const chassisReceiveData = new ChassisReceiveData();

// 导出到全局作用域
if (typeof window !== 'undefined') {
    window.chassisReceiveData = chassisReceiveData;
}

// CommonJS 模块导出
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        chassisReceiveData,
        ChassisReceiveData
    };
}
